package cn.ekuma.data.ui.android.editor;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.SearchView;
import android.widget.Toast;

import com.openbravo.data.basic.BasicException;
import com.openbravo.data.user.BaseBeanListRender;
import com.openbravo.data.user.I_AndroidBrowsableEditableData;

import java.util.ArrayList;
import java.util.List;

import cn.ekuma.android.ui.filter.BaseFilterPanel;
import cn.ekuma.data.ui.android.R;
import cn.ekuma.data.dao.I_DataLogic;
import cn.ekuma.data.dao.bean.I_BaseBean;
import cn.ekuma.data.ui.android.OnBaseBeanSelectedListener;
import cn.ekuma.epos.android.util.AbstractQueryAsyncTask;

/**
 * Created by Administrator on 2014/12/3.
 */
public abstract class AbstractPageEditorActivate<T extends I_BaseBean> extends Activity implements OnBaseBeanSelectedListener<T>,BaseBeanListRender,BaseFilterPanel.FilterPanelAdapter, ViewPager.OnPageChangeListener, SearchView.OnQueryTextListener {
    protected AbstractDAOJEditor<T> editor;
    protected I_DataLogic dlSales;
    protected DirtyManager dirty;
    protected I_AndroidBrowsableEditableData m_db;
    protected JNavigator navigator;
    protected JSaver saver;
    LinearLayout jEditorPage;
    ViewPager viewPager;
    ArrayList<View> pages;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dlSales = getDataLogic();
        dirty = new DirtyManager();

        setContentView(R.layout.page_editor);
        viewPager = (ViewPager) findViewById(R.id.page_editor);
        editor = createEditor();

        jEditorPage = new LinearLayout(this.getBaseContext());
        jEditorPage.setOrientation(LinearLayout.VERTICAL);

        m_db = getBrowsableEditableData();
        saver=new JSaver(m_db);

        navigator=new JNavigator(getBaseContext());
        navigator.setAndroidBrowsableEditableData(m_db);
        jEditorPage.addView(navigator);
        jEditorPage.addView(editor);

        pages=new ArrayList<View>();
        pages.add(getJListPage(m_db,this));
        pages.add(jEditorPage);

        viewPager.setAdapter(new EditorPagerAdapter());

        viewPager.setOnPageChangeListener(this);

        try {
            editor.activate();
            activate();
        } catch (BasicException e) {
            e.printStackTrace();
        }

    }


    @Override

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode== KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0){
            if(dirty.isDirty())
                try {
                    if(!m_db.actionClosingForm(AbstractPageEditorActivate.this))
                        return false;
                } catch (BasicException e) {
                    e.printStackTrace();
                }
        }
        return super.onKeyDown(keyCode,event);

    }


    public abstract void activate() throws BasicException;

    public abstract View getJListPage(I_AndroidBrowsableEditableData m_db,OnBaseBeanSelectedListener objSelectedListener);


    public AbstractDAOJEditor getEditor(){
        return editor;
    }

    /**添加ActionBar的Menu*/
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        int selectPage=viewPager.getCurrentItem();
        if(selectPage==1)
            getMenuInflater().inflate(R.menu.menu_edit, menu);
        else
            getMenuInflater().inflate(R.menu.menu_edit_list, menu);

        SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
        searchView.setOnQueryTextListener(this);
        return super.onCreateOptionsMenu(menu);
    }

    /**监听子菜单的点击事件*/
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        int id=menuItem.getItemId();
        if(id== R.id.action_new) {
            saver.jbtnNewActionPerformed();
        }else if(id== R.id.action_save) {
            saver.jbtnSaveActionPerformed();
        } else if( id==R.id.action_del) {
            saver.jbtnDeleteActionPerformed();
        }
        return false;
    }

    protected abstract I_AndroidBrowsableEditableData getBrowsableEditableData();

    protected abstract I_DataLogic getDataLogic();

    protected abstract AbstractDAOJEditor<T> createEditor();

    @Override
    public boolean onQueryTextChange(String newText) {
        return false;
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        if(viewPager.getCurrentItem()!=0)
              viewPager.setCurrentItem(0,true);
        onQuickSeach(query);
        return true;
    }

    public abstract void onQuickSeach(String inputText);

    public  class EditorPagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return pages.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object o) {
            return view==o;
        }

        @Override
        public Object instantiateItem(View container, int position) {

            try {
                ((ViewPager) container).addView(pages.get(position));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return pages.get(position);
        }
        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            try {
                ((ViewPager) container).addView(pages.get(position));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return pages.get(position);
        }

    }

    @Override
    public void baseBeanSelected(T obj, int position) {
        this.viewPager.setCurrentItem(1,true);
        try {
            m_db.moveTo(position);
        } catch (BasicException e) {
            e.printStackTrace();
        }
        //this.editor.writeValueEdit(obj);
    }



    public abstract class MyAsyncTask extends AbstractQueryAsyncTask<T> {

        public MyAsyncTask(Context c) {
            super(c);
        }

        @Override
        protected void queryResert(List<T> result) {
            try {
                m_db.loadData(result);
            } catch (BasicException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected void queryError(int type) {
            Toast.makeText(AbstractPageEditorActivate.this, "执行出错了", Toast.LENGTH_LONG).show();
        }
    }

    public static final int PAGE_CODE_1=0;
    public static final int PAGE_CODE_2=100;
    public static final int PAGE_CODE_3=200;


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        int page=requestCode<100?PAGE_CODE_1:requestCode<200?PAGE_CODE_2:PAGE_CODE_3;
        if(page==PAGE_CODE_2)
            editor.onActivityResult(requestCode,resultCode,data);
        else
            onActivityResult(page, requestCode, resultCode, data);
    }

     protected abstract  void onActivityResult(int page, int requestCode, int resultCode, Intent data);

    @Override
    public void onPageSelected(int i) {
        this.getWindow().invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }

    @Override
    public void onPageScrolled(int i, float v, int i2) {

    }
}
